<template>
  <div class="out-product-check-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="出库检验单编号">
          <el-input v-model="searchParams.outCheckCode" placeholder="请输入出库检验单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchParams.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="批次">
          <el-input v-model="searchParams.batch" placeholder="请输入批次" clearable></el-input>
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="searchParams.materialCode" placeholder="请输入物料编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchParams.materialName" placeholder="请输入物料名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="检验结果">
          <el-select v-model="searchParams.checkResult" placeholder="请选择检验结果" clearable style="width: 120px;">
            <el-option label="检验通过" value="检验通过"></el-option>
            <el-option label="检验不通过" value="检验不通过"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>新增
        </el-button>
        <el-button type="danger" @click="handleDelete" :disabled="!selectedRows.length">
          <el-icon>
            <Delete />
          </el-icon>删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        ref="outCheckTable"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
        highlight-current-row
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="checkCode" label="出库检验单编号" width="200"></el-table-column>
        <el-table-column prop="customerCode" label="客户编码" width="120"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="200"></el-table-column>
        <el-table-column prop="batch" label="批次" width="120"></el-table-column>
        <el-table-column prop="materailName" label="物料名称" width="120"></el-table-column>
        <el-table-column prop="productCode" label="产品编码" width="120"></el-table-column>
        <el-table-column prop="size" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="outNum" label="出库数量" width="100"></el-table-column>
        <el-table-column prop="checkNum" label="检验数量" width="100"></el-table-column>
        <el-table-column prop="lowNum" label="不合格数量" width="100"></el-table-column>
        <el-table-column prop="checkResult" label="检验结论" width="100">
          <template #default="scope">
            <el-tag :type="getResultType(scope.row.checkResult)">
              {{ scope.row.checkResult }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outDate" label="出库日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.outDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkDate" label="检验日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.checkDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkName" label="检验人员" width="100"></el-table-column>
        <el-table-column prop="approvalStatus" label="审批状态" width="100">
          <template #default="scope">
            <el-tag :type="getApprovalStatusType(scope.row.approvalStatus || '未提交')">
              {{ scope.row.approvalStatus || '未提交' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-if="scope.row.approvalStatus !== '已完成'">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ total }} 条</span>
        <el-select v-model="pageSize" placeholder="条/页" style="width: 100px" @change="handleSizeChange">
          <el-option :value="10" label="10条/页"></el-option>
          <el-option :value="20" label="20条/页"></el-option>
          <el-option :value="50" label="50条/页"></el-option>
          <el-option :value="100" label="100条/页"></el-option>
        </el-select>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
        <span class="page-info">
          前往 
          <el-input v-model="goToPage" style="width: 50px;" @keyup.enter="handleGoToPage"></el-input> 
          页
        </span>
      </div>
    </div>

    <!-- 添加出货检验单对话框 -->
    <el-dialog
      title="添加出货检验单"
      v-model="addDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="form-wrapper">
        <el-form :model="formData" label-width="120px" label-position="left" style="margin: 0 20px" class="out-check-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检验单编号" :required="true">
                <div class="input-with-switch">
                  <el-input v-model="formData.checkCode" placeholder="请输入出货检验单编号" style="width: 200px"></el-input>
                  <el-tooltip content="开启自动生成编号" placement="top">
                    <el-switch
                      v-model="autoGenerateCode"
                      @change="handleAutoGenerateChange"
                      active-color="#13ce66"
                      inline-prompt
                      active-text="自动"
                      inactive-text="手动"
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col  >
              <el-form-item label="检验单名称" class="check-name-input">
                <el-input v-model="formData.checkName" placeholder="请输入内容" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产品编码" :required="true">
                <div class="input-with-button">
                  <el-input v-model="formData.productCode" placeholder="请选择产品" readonly></el-input>
                  <el-button type="primary" @click="openProductDialog">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料名称">
                <el-input v-model="formData.materialName" placeholder="请输入物料名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号">
                <el-input v-model="formData.size" placeholder="请输入规格型号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input type="textarea" v-model="formData.descs" resize="none" rows="3"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户编码" :required="true">
                <div class="input-with-button">
                  <el-input v-model="formData.customerCode" placeholder="请选择客户" readonly></el-input>
                  <el-button type="primary" @click="openMaterialDialog">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称">
                <el-input v-model="formData.customerName" placeholder="客户名称" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="批次">
                <el-input v-model="formData.batch" placeholder="请输入批次"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="出库数量" :required="true">
                <el-input-number v-model="formData.outNum" :min="0" :precision="0" :step="1" :controls="true" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验数量" :required="true">
                <el-input-number v-model="formData.checkNum" :min="0" :precision="0" :step="1" :controls="true" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="不合格数量">
                <el-input-number v-model="formData.lowNum" :min="0" :precision="0" :step="1" :controls="true" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="出库日期" :required="true">
                <el-date-picker 
                  v-model="formData.outDate" 
                  type="date" 
                  placeholder="请选择出库日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验日期" :required="true">
                <el-date-picker 
                  v-model="formData.checkDate" 
                  type="date" 
                  placeholder="请选择检验日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验结果">
                <el-select v-model="formData.checkResult" placeholder="请选择检验结果">
                  <el-option label="检验通过" value="检验通过"></el-option>
                  <el-option label="检验不通过" value="检验不通过"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">保 存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 修改出货检验单对话框 -->
    <el-dialog
      title="修改出货检验单"
      v-model="editDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="form-wrapper">
        <el-form :model="formData" label-width="120px" label-position="left" style="margin: 0 20px" class="out-check-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检验单编号" :required="true">
                <div class="input-with-switch">
                  <el-input v-model="formData.checkCode" placeholder="请输入出货检验单编号" style="width: 200px"></el-input>
                  <el-tooltip content="开启自动生成编号" placement="top">
                    <el-switch
                      v-model="autoGenerateCode"
                      @change="handleAutoGenerateChange"
                      active-color="#13ce66"
                      inline-prompt
                      active-text="自动"
                      inactive-text="手动"
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验单名称" class="check-name-input">
                <el-input v-model="formData.checkName" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产品编码" :required="true">
                <div class="input-with-button">
                  <el-input v-model="formData.productCode" placeholder="请选择产品" readonly></el-input>
                  <el-button type="primary" @click="openProductDialog">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料名称">
                <el-input v-model="formData.materialName" placeholder="请输入物料名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号">
                <el-input v-model="formData.size" placeholder="请输入规格型号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input type="textarea" v-model="formData.descs" resize="none" rows="3"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户编码" :required="true">
                <div class="input-with-button">
                  <el-input v-model="formData.customerCode" placeholder="请选择客户" readonly></el-input>
                  <el-button type="primary" @click="openMaterialDialog">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称">
                <el-input v-model="formData.customerName" placeholder="客户名称" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="批次">
                <el-input v-model="formData.batch" placeholder="请输入批次"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="出库数量" :required="true">
                <el-input-number v-model="formData.outNum" :min="0" :precision="0" :step="1" :controls="true" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验数量" :required="true">
                <el-input-number v-model="formData.checkNum" :min="0" :precision="0" :step="1" :controls="true" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="不合格数量">
                <el-input-number v-model="formData.lowNum" :min="0" :precision="0" :step="1" :controls="true" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="出库日期" :required="true">
                <el-date-picker 
                  v-model="formData.outDate" 
                  type="date" 
                  placeholder="请选择出库日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验日期" :required="true">
                <el-date-picker 
                  v-model="formData.checkDate" 
                  type="date" 
                  placeholder="请选择检验日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验结果">
                <el-select v-model="formData.checkResult" placeholder="请选择检验结果">
                  <el-option label="检验通过" value="检验通过"></el-option>
                  <el-option label="检验不通过" value="检验不通过"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdate">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 产品搜索对话框 -->
    <el-dialog
      title="选择产品"
      v-model="productDialogVisible"
      width="1300px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="product-dialog"
    >
      <div class="search-dialog-container">
        <!-- 左侧产品类型树 -->
        <div class="left-tree">
          <h3>产品类型</h3>
          <el-input
            v-model="productTypeFilterText"
            placeholder="输入关键字过滤"
            clearable
          />
          <el-tree
            ref="productTypeTree"
            :data="productTypeTreeData"
            :props="{ label: 'name' }"
            node-key="id"
            highlight-current
            :filter-node-method="filterProductTypeNode"
            @node-click="handleProductTypeClick"
          ></el-tree>
        </div>
        
        <!-- 右侧产品列表 -->
        <div class="right-content">
          <!-- 搜索表单 -->
          <div class="search-header">
            <el-form :inline="true" :model="productSearchParams" class="search-form">
              <el-form-item label="物料编码">
                <el-input v-model="productSearchParams.productCode" placeholder="请输入物料编码" clearable></el-input>
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input v-model="productSearchParams.productName" placeholder="请输入物料名称" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchProducts">
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="resetProductSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 产品表格 -->
          <div class="table-wrapper">
            <el-table
              :data="productTableData"
              style="width: 100%"
              border
              highlight-current-row
              @row-click="selectProduct"
              height="400"
            >
              <el-table-column prop="productCode" label="物料编码" width="120" fixed></el-table-column>
              <el-table-column prop="productName" label="物料名称" width="150" show-overflow-tooltip></el-table-column>
              <el-table-column prop="specModel" label="规格型号" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column prop="flats" label="片" width="80"></el-table-column>
              <el-table-column prop="flatsMaterial" label="元器件" width="120"></el-table-column>
              <el-table-column prop="descs" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="primary" @click.stop="selectProduct(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <span class="total-text">共 {{ productTotal }} 条</span>
            <el-pagination
              layout="prev, pager, next"
              :total="productTotal"
              :page-size="10"
              :current-page="productCurrentPage"
              @current-change="handleProductPageChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 客户搜索对话框 -->
    <el-dialog
      title="选择客户"
      v-model="customerDialogVisible"
      width="1100px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="search-dialog-container">
        <!-- 搜索表单 -->
        <div class="search-header">
          <el-form :inline="true" :model="customerSearchParams" class="search-form">
            <el-form-item label="客户编码">
              <el-input v-model="customerSearchParams.custCode" placeholder="请输入客户编码" clearable></el-input>
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input v-model="customerSearchParams.custName" placeholder="请输入客户名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="客户简称">
              <el-input v-model="customerSearchParams.custShortName" placeholder="请输入客户简称" clearable></el-input>
            </el-form-item>
            <el-form-item label="是否启用">
              <el-select v-model="customerSearchParams.isEnable" placeholder="请选择" clearable style="width: 120px;">
                <el-option :value="1" label="是"></el-option>
                <el-option :value="0" label="否"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchCustomers">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetCustomerSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 客户表格 -->
        <div class="table-wrapper">
          <el-table
            :data="customerTableData"
            style="width: 100%"
            border
            highlight-current-row
            @row-click="selectCustomer"
            height="400"
          >
            <el-table-column prop="customerCode" label="客户编码" width="120" fixed></el-table-column>
            <el-table-column prop="customerName" label="客户名称" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column prop="shortName" label="客户简称" width="150"></el-table-column>
            <el-table-column prop="contactPerson" label="联系人" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click.stop="selectCustomer(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <span class="total-text">共 {{ customerTotal }} 条</span>
          <el-pagination
            layout="prev, pager, next"
            :total="customerTotal"
            :page-size="10"
            :current-page="customerCurrentPage"
            @current-change="handleCustomerPageChange"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import http from '@/api/http';
import { Search, Delete, Plus, Document } from '@element-plus/icons-vue';

const router = useRouter();

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref([]);

// 选中行
const selectedRows = ref([]);

// 分页参数
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const goToPage = ref(1);

// 搜索参数
const searchParams = reactive({
  outCheckCode: '',
  customerName: '',
  batch: '',
  materialCode: '',
  materialName: '',
  checkResult: ''
});

// 产品搜索对话框
const productDialogVisible = ref(false);
const productSearchParams = reactive({
  productCode: '',
  productName: '',
  productType: ''
});
const productTableData = ref([]);
const productTotal = ref(0);
const productCurrentPage = ref(1);
const productTypeTreeData = ref([]);
const productTypeFilterText = ref('');
const productTypeTree = ref(null);

// 客户搜索对话框
const customerDialogVisible = ref(false);
const customerSearchParams = reactive({
  custCode: '',
  custName: '',
  custShortName: '',
  isEnable: 1
});
const customerTableData = ref([]);
const customerTotal = ref(0);
const customerCurrentPage = ref(1);

// 对话框相关
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

// 表单数据
const formData = reactive({
  id: '',
  checkCode: '',
  checkName: '',
  batch: '',
  productCode: '',
  outNum: 1,
  checkNum: 1,
  lowNum: 0,
  outDate: '',
  checkDate: '',
  checkResult: '检验通过',
  customerCode: '',
  descs: ''
});

// 自动生成编号
const autoGenerateCode = ref(true);

// 生成检验单编号
const generateCheckCode = () => {
  // 生成格式为OQC加上年月日时分秒的编号
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  formData.checkCode = `OQC${year}${month}${day}${hours}${minutes}${seconds}`;
};

// 自动生成编号变化
const handleAutoGenerateChange = (val) => {
  if (val) {
    // 自动生成编号
    generateCheckCode();
  } else {
    // 清空编号，允许手动输入
    formData.checkCode = '';
  }
};

// 获取产品类型树数据
const fetchProductTypeTree = async () => {
  try {
    const response = await http.get('/api/OutProductCheck/GetMaterialCatalogList');
    console.log("产品类型树",response);
    
    if (response && response.status) {
      productTypeTreeData.value = formatTreeData(response.data);
    } else {
      productTypeTreeData.value = [];
      ElMessage.warning('获取产品类型失败');
    }
  } catch (error) {
    console.error('获取产品类型树出错:', error);
    productTypeTreeData.value = [];
  }
};

// 格式化树形数据
const formatTreeData = (data) => {
  if (!data || !Array.isArray(data)) return [];
  
  return data.map(item => {
    const node = {
      id: item.id,
      name: item.classifyName,
      children: item.children ? formatTreeData(item.children) : []
    };
    return node;
  });
};

// 产品类型点击事件
const handleProductTypeClick = (data) => {
  productSearchParams.productType = data.name;
  searchProducts();
};

// 搜索产品
const searchProducts = async () => {
  try {
    const params = {
      pageIndex: productCurrentPage.value,
      pageSize: 10,
      materailCode: productSearchParams.productCode,
      materailName: productSearchParams.productName,
      classifyName: productSearchParams.productType
    };
    
    const response = await http.post('/api/OutProductCheck/GetMaterialList', params);
    
    if (response && response.rows) {
      productTableData.value = response.rows.map(item => ({
        productCode: item.materialCode,
        productName: item.materialName,
        specModel: item.specification,
        flats: item.flats,
        flatsMaterial: item.flatsMaterial,
        descs: item.descs,
        unit: '',
        productType: '',
        category: '',
        createTime: ''
      })) || [];
      productTotal.value = response.total || 0;
    } else {
      productTableData.value = [];
      productTotal.value = 0;
    }
  } catch (error) {
    console.error('搜索产品出错:', error);
    productTableData.value = [];
    productTotal.value = 0;
  }
};

// 搜索客户
const searchCustomers = async () => {
  try {
    const params = {
      pageIndex: customerCurrentPage.value,
      pageSize: 10,
      custCode: customerSearchParams.custCode,
      custName: customerSearchParams.custName,
      custPhone: '',
      isEnable: customerSearchParams.isEnable
    };
    
    const response = await http.post('/api/OutProductCheck/GetCustomerList', params);
    console.log("客户列表", response);
    
    if (response && response.rows) {
      customerTableData.value = response.rows.map(item => ({
        customerCode: item.custCode,
        customerName: item.custName,
        shortName: item.custAbbreviation || '',
        contactPerson: item.conPerson || '',
        contactPhone: item.custPhone || '',
      })) || [];
      customerTotal.value = response.total || 0;
    } else {
      customerTableData.value = [];
      customerTotal.value = 0;
    }
  } catch (error) {
    console.error('搜索客户出错:', error);
    customerTableData.value = [];
    customerTotal.value = 0;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  // 如果日期已经是格式化的，直接返回
  if (typeof dateString === 'string' && dateString.includes('-')) {
    return dateString;
  }
  
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString;
  }
};

// 获取检验结果类型
const getResultType = (result) => {
  if (!result) return 'info';
  
  if (result.includes('通过')) {
    return 'success';
  } else if (result.includes('不通过')) {
    return 'danger';
  } else {
    return 'info';
  }
};

// 获取审批状态类型
const getApprovalStatusType = (status) => {
  if (!status) return 'info';
  
  switch (status) {
    case '已完成':
      return 'success';
    case '已确认':
      return 'success';
    case '已提交':
      return 'warning';
    default:
      return 'info';
  }
};

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      checkCode: searchParams.outCheckCode,
      customerName: searchParams.customerName,
      batch: searchParams.batch,
      materialCode: searchParams.materialCode,
      materialName: searchParams.materialName,
      checkResult: searchParams.checkResult
    };
    
    // API调用
    const response = await http.post('/api/OutProductCheck/GetOutProductCheckList', params);
    console.log("response", response);
    
    if (response) {
      tableData.value = response.rows || [];
      total.value = response.total || 0;
    } else {
      ElMessage.error(response?.msg || '获取数据失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败，请稍后再试');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchParams).forEach(key => {
    searchParams[key] = '';
  });
  currentPage.value = 1;
  fetchData();
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key !== 'outNum' && key !== 'checkNum' && key !== 'lowNum' && key !== 'checkResult') {
      formData[key] = '';
    } else if (key === 'outNum' || key === 'checkNum') {
      formData[key] = 1;
    } else if (key === 'lowNum') {
      formData[key] = 0;
    } else if (key === 'checkResult') {
      formData[key] = '检验通过';
    }
  });
};

// 新增按钮点击事件
const handleAdd = () => {
  resetForm();
  addDialogVisible.value = true;
  // 根据自动生成编号的状态生成编号
  if (autoGenerateCode.value) {
    generateCheckCode();
  }
};

// 编辑按钮点击事件
const handleEdit = (row) => {
  // 直接将行数据填充到表单中
  formData.id = row.id;
  formData.checkCode = row.checkCode;
  formData.checkName = row.checkName;
  formData.batch = row.batch;
  formData.productCode = row.productCode;
  formData.materialName = row.materailName; // 注意这里使用materailName而不是materialName
  formData.size = row.size;
  formData.outNum = row.outNum;
  formData.checkNum = row.checkNum;
  formData.lowNum = row.lowNum;
  formData.outDate = row.outDate;
  formData.checkDate = row.checkDate;
  formData.checkResult = row.checkResult || '检验通过';
  formData.customerCode = row.customerCode;
  formData.customerName = row.customerName;
  formData.descs = row.descs;
  
  // 直接打开编辑对话框
  editDialogVisible.value = true;
};

// 查看
const handleView = (row) => {
  router.push(`/mymes/qualityassurance/ViewOutProductCheck?id=${row.id}`);
};

// 删除
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  
  const ids = selectedRows.value.map(row => row.id);
  
  ElMessageBox.confirm('确认删除选中的记录?', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await http.post(`/api/OutProductCheck/DelOutProductCheck?ids=${ids}`);
      
      if (response && response.status) {
        ElMessage.success('删除成功');
        fetchData();
      } else {
        ElMessage.error(response?.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后再试');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchData();
};

// 跳转到指定页
const handleGoToPage = () => {
  const page = parseInt(goToPage.value);
  if (page && page > 0 && page <= Math.ceil(total.value / pageSize.value)) {
    currentPage.value = page;
    fetchData();
  } else {
    ElMessage.warning('请输入有效的页码');
  }
};

// 保存新增检验单
const handleSave = async () => {
  try {
    // 表单验证
    if (!validateForm()) {
      return;
    }
    
    // 准备提交的数据
    const submitData = {
      id: 0,
      checkCode: formData.checkCode,
      checkName: formData.checkName,
      batch: formData.batch,
      productCode: formData.productCode,
      outNum: formData.outNum,
      checkNum: formData.checkNum,
      lowNum: formData.lowNum,
      outDate: formatDateForSubmit(formData.outDate),
      checkDate: formatDateForSubmit(formData.checkDate),
      checkResult: formData.checkResult,
      customerCode: formData.customerCode,
      descs: formData.descs
    };
    
    console.log("提交的表单", submitData);
    const response = await http.post('/api/OutProductCheck/AddOutProductCheck', submitData);
    
    if (response && response.status) {
      ElMessage.success('添加成功');
      addDialogVisible.value = false;
      fetchData(); // 重新加载表格数据
    } else {
      ElMessage.error(response?.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加出错:', error);
    ElMessage.error('添加失败，请稍后再试');
  }
};

// 格式化日期为提交格式
const formatDateForSubmit = (date) => {
  if (!date) return '';
  
  if (typeof date === 'string') {
    // 如果已经是字符串格式，检查格式是否正确
    if (date.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)) {
      return date;
    }
    // 尝试转换为Date对象
    date = new Date(date);
  }
  
  if (date instanceof Date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
  }
  
  return '';
};

// 保存修改检验单
const handleUpdate = async () => {
  try {
    // 表单验证
    if (!validateForm()) {
      return;
    }
    
    // 准备提交的数据
    const submitData = {
      id: formData.id,
      checkCode: formData.checkCode,
      checkName: formData.checkName,
      batch: formData.batch,
      productCode: formData.productCode,
      outNum: formData.outNum,
      checkNum: formData.checkNum,
      lowNum: formData.lowNum,
      outDate: formatDateForSubmit(formData.outDate),
      checkDate: formatDateForSubmit(formData.checkDate),
      checkResult: formData.checkResult,
      customerCode: formData.customerCode,
      descs: formData.descs
    };
    
    console.log("提交的修改表单", submitData);
    const response = await http.post('/api/OutProductCheck/UpdOutProductCheck', submitData);
    
    if (response && response.status) {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      fetchData(); // 重新加载表格数据
    } else {
      ElMessage.error(response?.msg || '修改失败');
    }
  } catch (error) {
    console.error('修改出错:', error);
    ElMessage.error('修改失败，请稍后再试');
  }
};

// 表单验证
const validateForm = () => {
  // 必填字段验证
  const requiredFields = [
    { key: 'checkCode', name: '检验单编号' },
    { key: 'productCode', name: '产品编码' },
    { key: 'customerCode', name: '客户编号' },
    { key: 'outNum', name: '出库数量' },
    { key: 'checkNum', name: '检验数量' },
    { key: 'outDate', name: '出库日期' },
    { key: 'checkDate', name: '检验日期' }
  ];
  
  for (const field of requiredFields) {
    if (!formData[field.key]) {
      ElMessage.warning(`请输入${field.name}`);
      return false;
    }
  }
  
  return true;
};

// 打开产品搜索对话框
const openProductDialog = () => {
  productDialogVisible.value = true;
  fetchProductTypeTree();
  searchProducts();
};

// 选择产品
const selectProduct = (row) => {
  formData.productCode = row.productCode;
  productDialogVisible.value = false;
};

// 产品分页变化
const handleProductPageChange = (page) => {
  productCurrentPage.value = page;
  searchProducts();
};

// 过滤产品类型节点
const filterProductTypeNode = (value, data) => {
  if (!value) return true;
  return data.name.toLowerCase().includes(value.toLowerCase());
};

// 监听产品类型过滤文本变化
watch(productTypeFilterText, (val) => {
  productTypeTree.value?.filter(val);
});

// 重置产品搜索
const resetProductSearch = () => {
  productSearchParams.productCode = '';
  productSearchParams.productName = '';
  productSearchParams.productType = '';
  searchProducts();
};

// 打开客户搜索对话框
const openCustomerDialog = () => {
  customerDialogVisible.value = true;
  searchCustomers();
};

// 打开物料选择对话框
const openMaterialDialog = () => {
  customerDialogVisible.value = true;
  // 重置搜索参数
  resetCustomerSearch();
  // 加载客户列表
  searchCustomers();
};

// 选择客户
const selectCustomer = (row) => {
  formData.customerCode = row.customerCode;
  formData.customerName = row.customerName;
  customerDialogVisible.value = false;
};

// 客户分页变化
const handleCustomerPageChange = (page) => {
  customerCurrentPage.value = page;
  searchCustomers();
};

// 重置客户搜索
const resetCustomerSearch = () => {
  customerSearchParams.custCode = '';
  customerSearchParams.custName = '';
  customerSearchParams.custShortName = '';
  customerSearchParams.isEnable = 1;
  searchCustomers();
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.out-product-check-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
  
  .search-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }
  }
  
  .table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .table-header {
      margin-bottom: 20px;
      display: flex;
      gap: 10px;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      
      .total-text {
        margin-right: 15px;
      }
      
      .page-info {
        margin-left: 15px;
        display: flex;
        align-items: center;
      }
    }
  }

  .form-wrapper {
    max-height: 60vh;
    overflow-y: auto;
    padding: 10px 0;
    
    .el-form-item {
      margin-bottom: 18px;
      
      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #606266;
        text-align: left;
      }
    }
    
    .el-row {
      margin-bottom: 5px;
    }
    
    :deep(.el-input__inner) {
      border-radius: 4px;
    }
    
    :deep(.el-textarea__inner) {
      border-radius: 4px;
    }
    
    :deep(.el-select) {
      width: 100%;
    }
    
    :deep(.el-date-editor) {
      width: 100%;
    }
  }

  .input-with-button {
    display: flex;
    align-items: center;
    
    .el-input {
      flex: 1;
      
      :deep(.el-input__inner) {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-right: none;
      }
    }
    
    .el-button {
      margin-left: 0;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      padding: 8px 15px;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }

  .input-with-switch {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    
    .el-input {
      width: auto !important;
      flex: 1;
      min-width: 200px;
    }
    
    .switch-container {
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      padding: 5px 10px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      white-space: nowrap;
      
      .switch-label {
        margin-right: 5px;
        font-size: 13px;
        color: #606266;
      }
    }
    
    .el-tooltip {
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      padding: 5px 10px;
      border-radius: 4px;
      white-space: nowrap;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }

  // 添加检验单名称样式类
  .check-name-input {
  //  margin-left: 60px;
    .el-input {
      width: 380px !important;
    }
  }

  .search-dialog-container {
    display: flex;
    height: 500px;
    flex-direction: column;
    
    .search-header {
      margin-bottom: 15px;
      
      .search-form {
        background-color: #f9fafc;
        padding: 15px;
        border-radius: 4px;
        display: flex;
        flex-wrap: wrap;
        
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;
        }
      }
    }
    
    .table-wrapper {
      flex: 1;
      overflow: hidden;
      
      .el-table {
        height: 100%;
      }
    }
    
    .left-tree {
      width: 220px;
      border-right: 1px solid #dcdfe6;
      padding: 10px;
      overflow-y: auto;
      background-color: #f9fafc;
      border-radius: 4px 0 0 4px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 15px;
        font-size: 16px;
        color: #303133;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;
      }
      
      .el-input {
        margin-bottom: 15px;
      }
      
      :deep(.el-tree) {
        background-color: transparent;
        
        .el-tree-node__content {
          height: 32px;
          
          &:hover {
            background-color: #ecf5ff;
          }
        }
        
        .el-tree-node.is-current > .el-tree-node__content {
          background-color: #ecf5ff;
          color: #409eff;
          font-weight: 500;
        }
      }
    }
    
    .right-content {
      flex: 1;
      padding: 10px 15px;
      display: flex;
      flex-direction: column;
      
      .search-form {
        margin-bottom: 15px;
        padding: 15px;
        background-color: #f9fafc;
        border-radius: 4px;
        
        .el-form-item {
          margin-bottom: 10px;
          margin-right: 15px;
        }
        
        .el-button {
          padding: 8px 15px;
        }
      }
      
      .el-table {
        flex: 1;
        overflow-y: auto;
        
        :deep(.el-table__header) {
          th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 600;
            height: 45px;
          }
        }
        
        :deep(.el-table__row) {
          cursor: pointer;
          
          &:hover {
            background-color: #f5f7fa;
          }
          
          &.current-row {
            background-color: #ecf5ff;
          }
        }
      }
      
      .pagination-container {
        margin-top: 15px;
        display: flex;
        justify-content: center;
      }
    }
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  
  .el-dialog__header {
    background-color: #f5f7fa;
    padding: 15px 20px;
    margin-right: 0;
    border-bottom: 1px solid #ebeef5;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      
      .el-button {
        padding: 9px 20px;
        font-size: 14px;
        
        & + .el-button {
          margin-left: 12px;
        }
      }
    }
  }
}

// 产品对话框特殊样式
.product-dialog {
  .search-dialog-container {
    flex-direction: row !important;
    
    .left-tree {
      height: 100%;
    }
    
    .right-content {
      height: 100%;
      overflow: hidden;
    }
  }
}

// 数字输入框样式
:deep(.el-input-number) {
  .el-input-number__decrease, 
  .el-input-number__increase {
    background-color: #f5f7fa;
    border-color: #dcdfe6;
    color: #606266;
    
    &:hover {
      color: #409eff;
    }
  }
  
  .el-input__inner {
    text-align: center;
    font-weight: bold;
  }
}

// 添加下面的样式以确保表单标签正常显示
:deep(.el-form) {
  .el-form-item {
    .el-form-item__label {
      display: inline-block;
      text-align: right;
      vertical-align: middle;
      font-size: 14px;
      color: #606266;
      font-weight: 500;
      line-height: 32px;
      padding: 0 12px 0 0;
    }
  }
  
  &.el-form--label-left {
    .el-form-item__label {
      text-align: left;
    }
  }
}

// 自定义表单样式
.out-check-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;
    
    .el-form-item__label {
      display: block !important;
      text-align: left !important;
      color: #303133 !important; 
      font-weight: 500 !important;
      line-height: 1.5 !important;
      margin-bottom: 8px !important;
    }
    
    .el-form-item__label-wrap {
      display: block;
    }
    
    .el-form-item__content {
      margin-left: 0 !important;
    }
    
    &.is-required {
      .el-form-item__label:before {
        content: '*';
        color: #f56c6c;
        margin-right: 4px;
      }
    }
  }
}

// 全局样式
:deep(.el-form-item[label="检验单名称"]) {
  .el-input {
    width: 280px !important;
  }
}
</style> 